from nonebot import on_startswith
from nonebot.adapters import Event
import markdown2
from xhtml2pdf import pisa
import os
import glob
from nonebot.adapters.onebot.v11 import Message, MessageSegment, Bot, Event
# import io
# from PIL import Image
# import fitz
# import base64




# from markdown.extensions.codehilite import CodeHiliteExtension
# from markdown.extensions.toc import TocExtension

# from mdx_math import MathExtension

from markdown_it import MarkdownIt
from mdit_py_plugins.front_matter import front_matter_plugin
from mdit_py_plugins.footnote import footnote_plugin
from mdit_py_plugins.texmath import texmath_plugin

import requests


md = (
    MarkdownIt('commonmark', {'breaks':True,'html':True})
    .use(front_matter_plugin)
    .use(footnote_plugin)
    .use(texmath_plugin)
    .enable('table')
)



HCTI_API_ENDPOINT = "https://hcti.io/v1/image"
# Retrieve these from https://htmlcsstoimage.com/dashboard
HCTI_API_USER_ID = 'cd5b4068-f6e4-4ae9-9195-554963b27cc1'
HCTI_API_KEY = '7a3f3975-3b2e-4767-8a91-439dbc4ce43b'


command = on_startswith(("/md"))

@command.handle()
async def handler(event: Event):
    message = event.get_message().extract_plain_text().replace("/md", "", 1)

    tokens = md.parse(message)
    html_text = md.render(message)

    data = { 'html': html_text,
         'css': ".box { color: white; background-color: #0f79b9; padding: 10px; font-family: Roboto }",
         'google_fonts': "Roboto" }
    
    image = requests.post(url = HCTI_API_ENDPOINT, data = data, auth=(HCTI_API_USER_ID, HCTI_API_KEY))


    image_url = image.json()['url']


    d = requests.get(image_url).content

    

    await command.finish(MessageSegment.image(d))    


